<template>
  <div id="register">
    <el-dialog
      title="注册"
      width="300px"
      center
      :visible.sync="isRegister"
      :close-on-click-modal="false"
    >
      <el-form
        :model="RegisterUser"
        :rules="rules"
        status-icon
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <el-form-item prop="account">
          <el-input
            prefix-icon="el-icon-user-solid"
            placeholder="请输入账号"
            v-model="RegisterUser.account"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            prefix-icon="el-icon-view"
            type="password"
            placeholder="请输入密码"
            v-model="RegisterUser.password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="confirmPass">
          <el-input
            prefix-icon="el-icon-view"
            type="password"
            placeholder="请再次输入密码"
            v-model="RegisterUser.confirmPass"
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input
            prefix-icon="el-icon-view"
            placeholder="请输入手机号"
            v-model="RegisterUser.phone"
          ></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input
            prefix-icon="el-icon-message"
            placeholder="请输入邮箱"
            v-model="RegisterUser.email"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            size="medium"
            type="primary"
            @click="Register"
            style="width:100%;"
            >注册</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'MyRegister',
  props: ['register'],
  data() {
    // 用户名的校验方法
    let validateAccount = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('用户名不允许为空'))
      }
      // 用户名以字母开头,长度在5-16之间,允许字母数字下划线
      const accountRule = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/
      if (accountRule.test(value)) {
        this.$refs.ruleForm.validateField('checkPass')
        return callback()
      } else {
        return callback(new Error('字母开头,长度6-18之间,允许字母数字和下划线'))
      }
    }
    // 密码的校验方法
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入密码'))
      }
      // 密码以字母开头,长度在6-18之间,允许字母数字和下划线
      const passRule = /^[a-zA-Z]\w{5,17}$/
      if (passRule.test(value)) {
        this.$refs.ruleForm.validateField('checkPass')
        return callback()
      } else {
        return callback(new Error('字母开头,长度6-18之间,允许字母数字和下划线'))
      }
    }
    // 确认密码的校验方法
    let validateConfirmPass = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入确认密码'))
      }
      // 校验是否以密码一致
      if (
        this.RegisterUser.password != '' &&
        value === this.RegisterUser.password
      ) {
        this.$refs.ruleForm.validateField('checkPass')
        return callback()
      } else {
        return callback(new Error('两次输入的密码不一致'))
      }
    }
    // 手机号的校验方法
    let validatePhone = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入手机号'))
      }
      // 手机号正则表达式
      const phoneRule = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
      if (phoneRule.test(value)) {
        this.$refs.ruleForm.validateField('checkPass')
        return callback()
      } else {
        return callback(new Error('手机号输入错误'))
      }
    }

    // 邮箱的校验方法
    let validateEmail = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入邮箱'))
      }
      // 邮箱正则表达式
      const emailRule = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+/
      if (emailRule.test(value)) {
        this.$refs.ruleForm.validateField('checkPass')
        return callback()
      } else {
        return callback(new Error('邮箱格式输入错误'))
      }
    }

    return {
      isRegister: false, // 控制注册组件是否显示
      RegisterUser: {
        account: '',
        password: '',
        confirmPass: '',
        phone: '',
        email: ''
      },
      // 用户信息校验规则,validator(校验方法),trigger(触发方式),blur为在组件 Input 失去焦点时触发
      rules: {
        account: [
          { required: true, validator: validateAccount, trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        confirmPass: [
          { required: true, validator: validateConfirmPass, trigger: 'blur' }
        ],
        phone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        email: [{ required: true, validator: validateEmail, trigger: 'blur' }]
      }
    }
  },
  watch: {
    // 监听父组件传过来的register变量，设置this.isRegister的值
    register: function(val) {
      if (val) {
        console.log(val)
        this.isRegister = val
      }
    },
    // 监听this.isRegister变量的值，更新父组件register变量的值
    isRegister: function(val) {
      if (!val) {
        this.$refs['ruleForm'].resetFields()
        this.$emit('fromChild', val)
      }
    }
  },
  methods: {
    Register() {
      // 通过element自定义表单校验规则，校验用户输入的用户信息
      this.$refs['ruleForm'].validate(valid => {
        //如果通过校验开始注册
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/member/user/register'),
            method: 'post',
            data: this.$http.adornData({
              account: this.RegisterUser.account,
              password: this.RegisterUser.password,
              phone: this.RegisterUser.phone,
              email: this.RegisterUser.email
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                // 弹出通知框提示注册成功信息
                message: '注册成功！',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  // 隐藏注册组件
                  this.isRegister = false
                  window.location.reload()
                }
              })
              console.log(data)
              // token信息存在cookie中
              this.$cookie.set('mall_token', data.mall_token)
              // 获取登录信息存到本地
              let mall_user = JSON.stringify(data.mall_user)
              localStorage.setItem('mall_user', mall_user)
              // 登录信息存到vuex
              this.setUser(data.mall_user)
            } else {
              // 弹出通知框提示注册失败信息
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
<style></style>
